package com.szeastroc.controller;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.szeastroc.base.controller.BaseController;
import com.szeastroc.bean.system.SystemUser;

/**
 * Created by jie on 2018/1/16.
 */
@Controller
public class LoginController extends BaseController{

	@RequestMapping("/login")
	public String index(Model model){
		return "login.html";
	}


	// 登录提交地址和applicationontext-shiro.xml配置的loginurl一致。 (配置文件方式的说法)
	@RequestMapping(value="/login",method= RequestMethod.POST)
	public String login(HttpSession session, Model model,String username,String password) throws Exception {
		UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(usernamePasswordToken);   //完成登录
            if(subject.isAuthenticated()){
                Object object = subject.getPrincipal();
                if(object instanceof SystemUser){
                    SystemUser user=(SystemUser) subject.getPrincipal();
                    session.setAttribute("user", user);
                }
                return "main/main.html";
            }else{
                model.addAttribute("error", "请重新登录");
                return "login.html";
            }
		} catch (UnknownAccountException uae) {
			model.addAttribute("error", "未知账户");
		} catch (IncorrectCredentialsException ice) {
			model.addAttribute("error", "密码不正确");
		} catch (LockedAccountException lae) {
			model.addAttribute("error", "账户已锁定");
		} catch (ExcessiveAttemptsException eae) {
			model.addAttribute("error", "用户名或密码错误次数过多");
		} catch (AuthenticationException ae) {
			model.addAttribute("error", "用户名或密码不正确");
		}
		return "login.html";
	}

	@RequestMapping("/home")
	public String main(){
		Session session = SecurityUtils.getSubject().getSession();
		return "main/main.html";
	}

    @RequestMapping("/logout")
    public String logOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        session.removeAttribute("user");
        return "login";
    }
}
